const util = require('util');
const debug = util.debuglog('oil-game:luckDraw:dao');
const luckDraw = require('./luckDrawSchema');

// 获取幸运抽奖
exports.getLuckDrawInfo = function(uid) {
  debug("uid = %s  获取幸运抽奖", uid);
  return new Promise((resolve, reject) => {
    luckDraw.findOne({ uid }, {_id: 0 }, function (err, data) {
      if (err){
        debug("uid = %s  获取幸运抽奖异常 %s", uid, JSON.stringify(err));
        return reject(err);
      }
      debug("uid = %s  获取幸运抽奖成功 %s", uid, JSON.stringify(data));
      resolve(data);
    });
  });
}

// 增加幸运抽奖次数
exports.addLuckDrawNum = function(uid, num) {
  debug("uid = %s  num = %s  增加幸运抽奖次数", uid, num);
  return new Promise((resolve, reject) => {
    luckDraw.update({ uid }, { $inc: { luckDrawNum: num }}, function (err, data) {
      if (err){
        debug("uid = %s  num = %s  增加幸运抽奖次数异常  %s", uid, num, JSON.stringify(err));
        return reject(err);
      }
      debug("uid = %s  增加幸运抽奖次数成功 %s", uid, num, JSON.stringify(data));
      resolve(data);
    });
  });
}

// 保存幸运抽奖
exports.saveLuckDraw = function(luckDrawData){
  let {uid} = luckDrawData;
  debug("uid = %s 保存当前幸运抽奖 %s", uid, JSON.stringify(luckDrawData));
  return new Promise((resolve, reject) => {
    //检测宝箱数据是否为空
    if(!luckDrawData){ 
      debug("uid = %s 保存幸运抽奖信息，检测到数据为空，即将返回 %s", uid, JSON.stringify(luckDrawData));
      return reject({});
    }
    luckDraw.findOne({uid}, {_id: 1}, function(err,data){
      if(err){
        debug("uid = %s 查询本幸运抽奖数据异常 %s", uid, JSON.stringify(err));
        return reject(err);
      }
      if(data){   //更新文档
        luckDraw.update({uid}, luckDrawData, function(err, data){
          if(err){
            debug("uid = %s 更新本幸运抽奖数据异常 %s", uid, JSON.stringify(err));
            return reject(err);
          }
          debug("uid = %s 更新幸运抽奖数据成功 %s", uid, JSON.stringify(data));
          resolve(data);
        });
      }else{    //插入文档
        new luckDraw(luckDrawData).save((err, data)=> {
          if(err){
            debug("uid = %s 保存本幸运抽奖数据异常 %s", uid, JSON.stringify(err));
            return reject(err);
          }
          debug("uid = %s 保存幸运抽奖数据成功 %s", uid, JSON.stringify(data));
          resolve(data);
        });
      }
    });
  });
}
